import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Select, Image, DatePicker, Badge, Popover } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { QueryOccupyOrderListParams, OccupyOrder, OccupyOrderStatus } from './services';
import { queryOccupyOrderList } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StationSelect from '@/components/StationSelect';
import ColumnDesc from '@/components/ColumnDesc';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import { history, Access } from '@umijs/max'
import { jump2target } from '@/utils/common';

const OccupyOrderPage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryOccupyOrderListParams>()
  const [searchParams, setSearchParams] = useState<QueryOccupyOrderListParams>({
    pageNum: 1, pageSize: 10,
    beginTime: dayjs().subtract(31, 'days').format('YYYY-MM-DD 00:00:00'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  const list = useRequest(() => queryOccupyOrderList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [imgList, setImgList] = useState<string[]>([])

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      id: formValues.id,
      status: formValues.status,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stubId: formValues.stubId,
      infoType: formValues.infoType,
      telephone: formValues.telephone,
      beginTime: formValues.timeRange ? formValues.timeRange[0]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: formValues.timeRange ? formValues.timeRange[1]?.format('YYYY-MM-DD HH:mm:ss') : undefined,
      pageNum: 1,
    })
  }

  const jump2chargeOrderListPage = (record: OccupyOrder) => {
    jump2target(`/order/chargeOrder?orderId=${record.chargeOrderId || ''}`, {needRefresh: true})
  }

  const columns: ColumnsType<OccupyOrder> = [
    {
      title: '电站信息',
      dataIndex: 'stationName',
      width: 140,
      render: (val) => {
        return <Popover content={val}>
          <Ellipsis>{val}</Ellipsis>
        </Popover>
      }
    },
    {
      title: '订单号',
      dataIndex: 'id',
      width: 140,
    },
    {
      title: '用户手机号',
      dataIndex: 'telephone',
      width: 140,
    },
    {
      title: '充电信息',
      key: 'chargeInfo',
      width: 180,
      render: (_, record) => {
        return <ColumnDesc
          list={[
            {label: '车牌号', value: record.carPlat || '--'},
            {label: '枪编号', value: record.stubId || '--'},
            {label: '充电时间', value: record.chargeBeginTime ? `${record.chargeBeginTime}~${record.chargeEndTime || '至今'}` : '--'},
          ]}
        />
      }
    },
    {
      title: '占用信息',
      key: 'occupyInfo',
      width: 180,
      render: (_, record) => {
        let status: React.ReactNode = '--'
        switch (record.status) {
          case OccupyOrderStatus.占用中: status = <Badge status="processing" text="占用中" />; break
          case OccupyOrderStatus['占用结束(待支付)']: 
          case OccupyOrderStatus['占用结束(已支付)']: status = <Badge status="success" text="占用结束" />; break
        }
        return <ColumnDesc
          list={[
            {label: '占用状态', value: status},
            {label: '免费时长', value: record.freeTime ? `${record.freeTime}分钟` : '--'},
            {label: '计费时长', value: record.totalTime ? `${record.totalTime}分钟` : '--'},
            {label: '占用时长', value: record.totalTime ? `${record.totalTime + record.freeTime}分钟` : '--'},
            {label: '占用时间', value: `${record.beginTime}~${record.endTime || '至今'}`},
          ]}
        />
      }
    },
    {
      title: '交易信息',
      key: 'payInfo',
      width: 140,
      render: (_, record) => {
        let status: React.ReactNode = '--'
        let payment: string = '应付金额'
        switch (record.status) {
          case OccupyOrderStatus.占用中: break
          case OccupyOrderStatus['占用结束(待支付)']: 
            status = <Badge status="error" text="待支付" />
            break
          case OccupyOrderStatus['占用结束(已支付)']: 
            status = <Badge status="success" text={record.realPay ? '已支付' : '无需支付'} />
            payment = '实付金额'
            break
        }
        return <ColumnDesc
          list={[
            {label: '支付状态', value: status},
            {label: payment, value: status === '--' ? '--' : record.realPay},
          ]}
        />
      }
    },
    {
      title: '操作',
      key: 'operation',
      width: 80,
      fixed: 'right',
      render: (id: string, record) => {
        return <Space>
          <Access accessible={!!record.chargeOrderId}>
            <a onClick={() => jump2chargeOrderListPage(record)}>充电订单</a>
          </Access>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshOccupyOrderList', refresh)
    return () => {
      window.removeEventListener('refreshOccupyOrderList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchOccupyOrderForm' form={searchForm} onFinish={onFinish} initialValues={{timeRange: [dayjs().subtract(31, 'day'), dayjs()]}}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='订单号' name='id'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='订单状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(OccupyOrderStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='场站ID' name='station'>
                  <StationSelect />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='枪编号' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='用户手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label='占用时间' name='timeRange'>
                  <DatePicker.RangePicker showTime style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<OccupyOrder>
          rowKey='id'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <Image.PreviewGroup
        items={imgList}
        preview={{
          visible: imgList.length > 0,
          onVisibleChange: val => {
            if (!val) setImgList([])
          }
        }}
      >
      </Image.PreviewGroup>
    </div>
  );
};

export default OccupyOrderPage;
